import os

# 消费类别缩写映射
category_mapping = {
    "food": "餐饮",
    "stat": "文具",
    "trans": "交通",
    "fun": "娱乐",
    "other": "其他"
}


def load_records(path):
    try:
        with open(path, 'r', encoding='utf-8') as file:
            content = file.read()
            if content:
                return eval(content)
            return {}
    except FileNotFoundError:
        return {}
    except Exception as e:
        print(f"读取文件时出现错误: {e}")
        return {}


def save_records(path, data):
    try:
        with open(path, 'w', encoding='utf-8') as file:
            file.write(str(data))
    except Exception as e:
        print(f"保存文件时出现错误: {e}")


def input_records():
    records = {}
    while True:
        category_input = input("请输入消费类别（输入 q 结束录入）: ").strip().lower()
        if category_input == 'q':
            break
        category = category_mapping.get(category_input, category_input)
        if category not in ["餐饮", "文具", "交通", "娱乐", "其他"]:
            print("输入的消费类别不合法，请重新输入。")
            continue
        while True:
            try:
                amount = float(input(f"请输入 {category} 的消费金额: "))
                if amount <= 0:
                    print("消费金额必须为正数，请重新输入。")
                else:
                    break
            except ValueError:
                print("输入的金额不合法，请输入一个有效的正浮点数。")
        records[category] = records.get(category, 0) + amount
    return records


def main():
    file_path = "我的校园消费记录.txt"
    # 加载历史记录
    historical_records = load_records(file_path)
    # 收集本次输入
    new_records = input_records()
    # 合并记录
    for category, amount in new_records.items():
        historical_records[category] = historical_records.get(category, 0) + amount
    # 保存更新后的记录
    save_records(file_path, historical_records)
    # 输出统计信息
    print("\n各类别当前累计消费金额：")
    for category, amount in historical_records.items():
        print(f"{category}: {amount} 元")
    total_amount = sum(historical_records.values())
    print(f"总消费金额: {total_amount} 元")
    if historical_records:
        max_category = max(historical_records, key=historical_records.get)
        print(f"消费金额最高的类别: {max_category}")


if __name__ == "__main__":
    main()
